package ltd.sshine.networkclient.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringEncoder;
import ltd.sshine.networkclient.config.ClientConfig;
import ltd.sshine.networkclient.config.ServerConfig;
import ltd.sshine.networkclient.handler.ClientAuthChannelHandler;
import ltd.sshine.networkclient.service.ProxyService;

public class ClientUtils {

    private final ObjectMapper objectMapper;
    private final ServerConfig serverConfig;
    private final ClientConfig clientConfig;

    private final ProxyService proxyService;
    public ClientUtils(ObjectMapper objectMapper, ServerConfig serverConfig, ClientConfig clientConfig, ProxyService proxyService) {
        this.objectMapper = objectMapper;
        this.serverConfig = serverConfig;
        this.clientConfig = clientConfig;
        this.proxyService = proxyService;
    }

    public  Bootstrap createClientBootstrap() {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) {
                        JsonObjectDecoder jsonObjectDecoder = new JsonObjectDecoder();
                        StringEncoder stringEncoder = new StringEncoder();
                        ch.pipeline().addLast(
                                jsonObjectDecoder,
                                new ClientAuthChannelHandler(objectMapper, serverConfig, clientConfig, proxyService, jsonObjectDecoder,stringEncoder),
                                stringEncoder
                        );
                    }
                });
        return bootstrap;
    }
}
